package com.zwj.batch.api.xxl;

import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zwj.batch.core.batch.job.UserJob;
import com.zwj.batch.domain.bo.XxlJobBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/1/7 21:20
 */
@Slf4j
@Component
public class UserXxlJob {
    /**
     * batch用户job
     */
    @Resource
    private UserJob userJob;
    /**
     * batch调度器
     */
    @Resource
    private JobLauncher jobLauncher;
    /**
     * SpringBatch 参数构造器
     */
    @Resource
    private JobParametersBuilder jobParametersBuilder;

    /**
     * 学习batchJob用法
     *
     * @param param 参数
     * @return xxlJob响应值
     */
    @XxlJob("batchJobStudy")
    public ReturnT<String> beanJobHandler(String param) {
        log.info("==============学习batchJob用法start");
        XxlJobBO xxlJobBO = JSONUtil.toBean(param, XxlJobBO.class);
        //准备参数
        JobParameters jobParameters = jobParametersBuilder
                .addString("batchDate", xxlJobBO.getBatchDate())
                .addString("name", xxlJobBO.getName())
                .toJobParameters();
        //获取job
        Job job = userJob.batchJobStudy();
        try {
            //执行SpringBatch步骤
            jobLauncher.run(job, jobParameters);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("==============学习batchJob用法end");
        return ReturnT.SUCCESS;
    }
}
